package com.dat255.tentatime;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.dat255.tentatime.database.TTDbAdapter;

public class TodosOverview extends ListActivity {
	private TTDbAdapter dbHelper;
//	private static final int ACTIVITY_CREATE = 0;
	private static final int ACTIVITY_EDIT = 1;
//	private static final int DELETE_ID = Menu.FIRST + 1;
	private Cursor cursor;

	
/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);
		this.getListView().setDividerHeight(2);
		dbHelper = new TTDbAdapter(this);
		dbHelper.open();
		fillData();
		registerForContextMenu(getListView());
	}

	// Create the menu based on the XML defintion
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}




	// ListView and view (row) on which was clicked, position and
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(this, TodoDetails.class);
		i.putExtra(TTDbAdapter.KEY_ROWID, id);
		// Activity returns an result if called with startActivityForResult
		
		startActivityForResult(i, ACTIVITY_EDIT);
	}

	// Called with the result of the other activity
	// requestCode was the origin request code send to the activity
	// resultCode is the return code, 0 is everything is ok
	// intend can be use to get some data from the caller
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillData();

	}

	private void fillData() {
		cursor = dbHelper.fetchAllExams();
		startManagingCursor(cursor);

		String[] from = new String[] { TTDbAdapter.KEY_ID, TTDbAdapter.KEY_NAME };
		int[] to = new int[] { R.id.textCourseID, R.id.textCourseName };

		// Now create an array adapter and set it to display using our row
		SimpleCursorAdapter exams = new SimpleCursorAdapter(this,
				R.layout.result_row, cursor, from, to);
		setListAdapter(exams);
	}
	

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
}